package com.clothing.controller.app;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.clothing.bean.ArticleJson;
import com.clothing.bean.CommentJson;
import com.clothing.bean.MessageJson;
import com.clothing.controller.BaseController;
import com.clothing.entity.Article;
import com.clothing.entity.Article.Status;
import com.clothing.entity.Message.Type;
import com.clothing.entity.Comment;
import com.clothing.entity.CommentReply;
import com.clothing.entity.Message;
import com.clothing.entity.User;
import com.clothing.service.ArticleService;
import com.clothing.service.CommentReplyService;
import com.clothing.service.CommentService;
import com.clothing.service.MessageService;
import com.clothing.service.UserService;
import com.clothing.service.WxAppService;
import com.clothing.utils.AjaxMsg;
import com.clothing.utils.DateUtils;
import com.clothing.utils.Utils;
import com.clothing.utils.page.Page;
import com.clothing.utils.page.Pageable;
import com.clothing.utils.weixin.KeynoteItem;
import com.clothing.utils.weixin.TemplateMsg.WeixinTemplate;

/**
 * @ClassName: CommentController
 * @Description: TODO(Controller)
 * @author Charles.Tao
 * @date 2017年9月11日 下午2:01:18
 * @version 1.0
 */
@RequestMapping("/app/comment")
@Controller("appCommentController")
public class CommentController extends BaseController
{
    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentReplyService commentReplyService;
    
    @Autowired 
    private WxAppService wxAppService;
    
    @Autowired
    private MessageService messageService;

    /**
     * @Title: submit 
     * @Description: TODO(评论) 
     * @param @param articleId
     * @param @param content
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public String submit(Long articleId, String content)
    {
        if (Utils.isEmpty(content))
        {
            return getParameterErrorMsg();
        }

        Article article = articleService.find(articleId);

        if (null == article|| Status.pass != article.getStatus())
        {
            return getParameterErrorMsg();
        }

        User current = userService.getCurrent();
        Comment comment = new Comment();
        comment.setArticle(article);
        comment.setCreator(current);
        comment.setContent(content);
        article.setCommentQuantity(article.getCommentQuantity() + 1);
        commentService.comment(comment, article);
        User creator = article.getCreator();
        String url = "www.baidu.com";
        List<KeynoteItem> keynotes = new ArrayList<KeynoteItem>();
        keynotes.add(new KeynoteItem("keyword1", content, "#173177"));
        keynotes.add(new KeynoteItem("keyword2", DateUtils.f(comment.getCreateDate(), "yyyy-MM-dd"), "#173177"));
        keynotes.add(new KeynoteItem("keyword3", current.getNickname(), "#173177"));
        wxAppService.sendTemplateMsg(creator.getOpenid(), url, null, null, keynotes, WeixinTemplate.COMMENT_MESSAGE);
        
        return AjaxMsg.success("评论成功");
    }

    /**
     * @Title: reply 
     * @Description: TODO(评论回复) 
     * @param @param commentId
     * @param @param userId
     * @param @param content
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/reply", method = RequestMethod.POST)
    @ResponseBody
    public String reply(Long commentId, Long userId, String content)
    {
        if (Utils.isEmpty(content))
        {
            return AjaxMsg.failed("评论内容不能为空");
        }
        
        Comment comment = commentService.find(commentId);
        
        if (null == comment)
        {
            return getParameterErrorMsg();
        }
        
        User other = userService.find(userId);
        
        if (null == other)
        {
            return getParameterErrorMsg();
        }
        
        User current = userService.getCurrent();
        
        if (current.getId().equals(userId))
        {
            return AjaxMsg.failed("不能回复自己");
        }
        
        CommentReply reply = new CommentReply();
        reply.setComment(comment);
        reply.setCreator(current);
        reply.setOther(other);
        reply.setContent(content);
        commentReplyService.reply(reply);

        return AjaxMsg.success();
    }

    /**
     * @Title: list 
     * @Description: TODO(列表) 
     * @param @param articleId
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getList.json", method = RequestMethod.GET)
    @ResponseBody
    public String list(Long articleId)
    {
        Article article = articleService.find(articleId);

        if (article == null)
        {
            return getParameterErrorMsg();
        }

        ArticleJson json = new ArticleJson();
        User user = article.getCreator();
        json.setPublishDate(article.getCreateDate());
        json.setContent(article.getContent());
        json.setImages(article.getFullImages());
        json.setUserId(user.getId());
        json.setNickname(user.getNickname());
        json.setHeadImgUrl(user.getHeadImgUrl());
        json.setCommentQuantity(article.getCommentQuantity());
        List<Comment> cList = article.getComments();
        
        if (!Utils.isEmpty(cList))
        {
            List<CommentJson> comments = new ArrayList<CommentJson>();

            for (Comment comment : cList)
            {
                User commentUser = comment.getCreator();
                CommentJson commentJson = new CommentJson();
                commentJson.setId(comment.getId());
                commentJson.setContent(comment.getContent());
                commentJson.setHeadImgUrl(commentUser.getHeadImgUrl());
                commentJson.setNickname(commentUser.getNickname());
                commentJson.setCommentDate(comment.getCreateDate());
                commentJson.setUserId(commentUser.getId());
                List<CommentReply> commentReplies = comment.getCommentReplies();

                if (!Utils.isEmpty(commentReplies))
                {
                    List<CommentJson> replies = new ArrayList<CommentJson>();

                    for (CommentReply commentReply : commentReplies)
                    {
                        User creator = commentReply.getCreator();
                        User other = commentReply.getOther();
                        CommentJson reply = new CommentJson();
                        reply.setContent(commentReply.getContent());
                        reply.setCreatorName(creator.getNickname());
                        reply.setOtherName(other.getNickname());
                        reply.setCommentDate(commentReply.getCreateDate());
                        reply.setCreatorId(creator.getId());
                        reply.setOtherId(other.getId());
                        replies.add(reply);
                    }

                    commentJson.setReplies(replies);
                }

                comments.add(commentJson);
            }
            
            json.setComments(comments);
        }

        return new AjaxMsg(true, json).toString();
    }
    
    /**
     * @Title: myCommentList 
     * @Description: TODO(我的评论列表) 
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/getMyCommentList.json", method = RequestMethod.GET)
    @ResponseBody
    public String myCommentList(Pageable pageable)
    {
        Long userId = userService.getCurrentId();
        Page<Message> page = messageService.findMessage(userId, pageable);
        JSONArray ja = null;
        
        if (page.getTotal() > 0)
        {
            ja = new JSONArray();
            
            for (Message message : page.getContent())
            {
                User user = message.getSender();
                MessageJson json = new MessageJson();
                json.setContent(message.getContent());
                json.setHeadImgUrl(user.getHeadImgUrl());
                json.setSendeDate(message.getCreateDate());
                json.setSenderId(user.getId());
                json.setSenderName(user.getNickname());
                json.setType(message.getType());
                
                if (Type.comment == message.getType())
                {
                    json.setArticleId(message.getFkId());
                }
                else if (Type.reply == message.getType())
                {
                    Comment comment = commentService.find(message.getFkId());
                    json.setArticleId(comment.getArticle().getId());
                }
                
                ja.add(json);
            }
        }
        
        return new AjaxMsg(true, page.getTotal(), ja).toString();
    }
}
